//
//  PostManage.m
//  PostDelivery
//
//  Created by wmz on 2020/6/18.
//  Copyright © 2020 wmz. All rights reserved.
//

#import "PostManage.h"
#if __has_include(<TUICore/TUILogin.h>)
#import <TUICore/TUILogin.h>
#endif
#if __has_include(<TXIMSDK_Plus_iOS/ImSDK_Plus.h>)
#import <TXIMSDK_Plus_iOS/ImSDK_Plus.h>
#endif
#import <SDImageCache.h>
static PostManage* postManage = nil;
@interface PostManage()
@end
@implementation PostManage
+ (instancetype)shareInstance{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        postManage = [[super allocWithZone:NULL] init];
        postManage.fontScale = 1;
        postManage.theme = @"normal";
    }) ;
    return postManage ;
}

- (void)updateWallet:(nullable PostNetWorkBock)block{
    [QDOrderNetWork.shareInstance requestMemberPurse:@{@"mId":GNFillEmpty(self.userModel.ids)} viewController:nil andBlock:^(id  _Nullable data, BOOL result) {
        if (result) {
            self.wallModel = [QDMyWalletModel yy_modelWithJSON:data];
            if (self.wallModel)
                PostUserSet([self.wallModel yy_modelToJSONString], @"wallModel")
        }
        if (block) block(data,result);
    }];
}

- (void)updateUser:(nullable PostNetWorkBock)block{
    if (!self.userCode || !self.token){
        if (block) block(nil,NO);
        return;
    }
    [CommonNetWork.shareInstance requestGetUserInfo:@{} viewController:nil andBlock:^(id  _Nullable data, BOOL result) {
        if (result) {
            self.userModel = [QDUserModel yy_modelWithJSON:data];
            if (self.userModel){
                [CommonNetWork.shareInstance requestGetMemberInfo:@{@"targetMember":GNFillEmpty(self.userModel.ids)} viewController:nil andBlock:^(id  _Nullable data1, BOOL result1) {
                    if (result1) {
                        self.userModel.visitor = data1[@"visitor"];
                        self.userModel.albums = data1[@"albums"];
                        self.userModel.favorites = data1[@"favorites"];
                        self.userModel.follower = data1[@"follower"];
                        self.userModel.follow = data1[@"follow"]?[data1[@"follow"] boolValue]:NO;
                        self.userModel.vip =  data1[@"vip"]?[data1[@"vip"] boolValue]:NO;
                    }
                    if (block) block(data1,result1);
                    PostUserSet([self.userModel yy_modelToJSONString], @"userModel")
                }];
            }else{
                if (block) block(nil,NO);
            }
        }
    }];
}

- (void)logout:(nullable NSString*)str root:(BOOL)root{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSDictionary* defaults = [defs dictionaryRepresentation];
    for (id key in defaults) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
    PostManage.shareInstance.userCode = nil;
    PostManage.shareInstance.token = nil;
    if (str) {
        [PostWindow pushLoginVC:str];
    }else{
        [PostWindow toLogonAction:root];
    }
}

- (void)loginTUIM:(nullable PostNetWorkBock)block{
    [CommonNetWork.shareInstance requestGetIM:@{@"mId":GNFillEmpty(self.userModel.ids)} viewController:nil andBlock:^(id  _Nullable data, BOOL result) {
        if (result) {
            self.userSig = data;
        #if __has_include(<TXIMSDK_Plus_iOS/ImSDK_Plus.h>)
            if (V2TIMManager.sharedInstance.getLoginStatus != 2) {
               #if __has_include(<TUICore/TUILogin.h>)
                [TUILogin login:PostManage.shareInstance.userModel.ids userSig:self.userSig succ:^{
                    NSLog(@"-----> 登录成功");
                } fail:^(int code, NSString *msg) {
                    NSLog(@"-----> 登录失败");
                }];
               #endif
            }
        #endif
        }
    }];
}

- (NSString*)getCacheSize{
    NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager * manager = [NSFileManager defaultManager];
    CGFloat size = 0;
    if ([manager fileExistsAtPath:path]) {
        NSArray * childFile = [manager subpathsAtPath:path];
        for (NSString * fileName in childFile) {
            NSString * absolutPath = [path stringByAppendingPathComponent:fileName];
            size = size + [manager attributesOfItemAtPath:absolutPath error:nil].fileSize;
        }
        size += [[SDImageCache sharedImageCache] totalDiskSize];;
    }
    if (size == 0) {
        return @"暂无缓存";
    }
    return [NSString stringWithFormat:@"%.2fM",size / 1024 / 1024];
}

-(void)cleanCache{
    NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray * childFile = [manager subpathsAtPath:path];
        for (NSString *fileName in childFile) {
            NSString * absolutPat = [path stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutPat error:nil];
        }
        [[SDImageCache sharedImageCache] clearMemory];
    }
}

- (BOOL)isLogin{
    return self.token && self.userModel;
}

- (NSString *)token{
    return PostUserGet(PostUserToken);
}

- (void)setToken:(NSString *)token{
    if (token) PostUserSet(token, PostUserToken);
}

- (void)setUserCode:(NSString *)userCode{
    if (userCode) PostUserSet(userCode, PostUserUserId);
}

- (NSString *)userCode{
    return PostUserGet(PostUserUserId)?:@"";
}

- (QDUserModel *)userModel{
    if (!_userModel) {
        _userModel = [QDUserModel yy_modelWithJSON:PostUserGet(@"userModel")];
    }
    return _userModel;
}

- (QDMyWalletModel *)wallModel{
    if (!_wallModel) {
        _wallModel = [QDMyWalletModel yy_modelWithJSON:PostUserGet(@"wallModel")];
    }
    return _wallModel;
}

- (NSDictionary *)payInfo{
    if (!_payInfo) {
        _payInfo = @{
            @(QDPayMethodTypeBalance):@"余额",
            @(QDPayMethodTypeWX):@"微信",
            @(QDPayMethodTypeZFB):@"支付宝",
        };
    }
    return _payInfo;
}

- (CGFloat)setUpSize:(NSInteger)size{
    CGFloat changeSize = size;
    if (PostWidth == 320) {
        changeSize -= 2;
    }else if (PostWidth==375){
        changeSize = size;
    }else{
        changeSize += 1.5;
    }
    return changeSize * postManage.fontScale;
}

- (UIColor*)setUpColor:(long)rgbValue{
    if ([postManage.theme isEqualToString:@"normal"]) {
        return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
    }
    return [UIColor whiteColor];
}

+ (id)allocWithZone:(struct _NSZone *)zone{
    return [PostManage shareInstance] ;
}

- (id)copyWithZone:(struct _NSZone *)zone{
    return [PostManage shareInstance] ;
}
@end
